package cn.springboot.erp.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.springboot.erp.commons.QueryParams;
import cn.springboot.erp.commons.ResponseResult;
import cn.springboot.erp.exception.CustomerException;
import cn.springboot.erp.exception.CustomerNameException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.springboot.erp.entity.Customers;
import cn.springboot.erp.service.CustomersService;
import cn.springboot.erp.mapper.CustomersMapper;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
* @author asus
* @description 针对表【customers】的数据库操作Service实现
* @createDate 2024-05-07 16:01:07
*/
@Service
@Transactional
public class CustomersServiceImpl extends ServiceImpl<CustomersMapper, Customers>
    implements CustomersService{

    @Override
    public ResponseResult listPage(QueryParams<Customers> queryParams) {
        //获取参数中的数据
        Customers searchParams = queryParams.getSearchParams();
        Integer page = queryParams.getPage();
        Integer limit = queryParams.getLimit();
        // 分页
        Page<Customers> customersPage = new Page<>(page, limit);
        // 数据查询
        LambdaQueryWrapper<Customers> lambda = new QueryWrapper<Customers>().lambda();
        lambda.like(StringUtils.isNotBlank(searchParams.getName()),Customers::getName,searchParams.getName())
                .like(StringUtils.isNotBlank(searchParams.getContactName()),Customers::getContactName,searchParams.getContactName())
                .orderByDesc(Customers::getCreateTime);
        baseMapper.selectPage(customersPage,lambda);
        return ResponseResult.Success()
                .data("total",customersPage.getTotal())
                .data("customerList",customersPage.getRecords());
    }

    @Override
    public ResponseResult importCustomer(MultipartFile file) throws Exception {
        // 判断文件是否为空
        if (file.isEmpty()){
            return ResponseResult.Fail().msg("请选择需要上传的文件");
        }
        InputStream inputStream = file.getInputStream();
        ImportParams importParams = new ImportParams();
        // 设置表头行数
        importParams.setHeadRows(1);
        // 设置标题行数
        importParams.setTitleRows(1);
        List<Customers> customerList = ExcelImportUtil.importExcel(inputStream, Customers.class, importParams);

        // 遍历数据
        customerList.forEach(customer->{
            // 获取客户名称
            String name = customer.getName();
            // 根据客户名称查询客户表
            LambdaQueryWrapper<Customers> lambda = new QueryWrapper<Customers>().lambda();
            lambda.eq(Customers::getName,name);
            Customers customers = baseMapper.selectOne(lambda);
            if (ObjectUtils.isNotNull(customers)){
                throw new CustomerNameException("客户名称已经存在："+name);
            }
            // 添加客户信息
            baseMapper.insert(customer);

        });

        return ResponseResult.Success().msg("批量导入成功");
    }

    @Override
    public void exportCustomer(HttpServletResponse response, Map<String, Object> params) throws IOException {
        // 获取参数中的数据
        Object name = params.get("name");
        Object contactName =  params.get("contactName");
        // 查询数据
        LambdaQueryWrapper<Customers> lambda = new QueryWrapper<Customers>().lambda();
        lambda.like(ObjectUtils.isNotNull(name),Customers::getName,name)
                .like(ObjectUtils.isNotNull(contactName),Customers::getContactName,contactName)
                .orderByDesc(Customers::getCreateTime);
        List<Customers> customersList = baseMapper.selectList(lambda);

        // 设置导出参数
        ExportParams exportParams = new ExportParams();
        // 设置工作簿表名
        exportParams.setSheetName("客户信息");
        // 设置客户信息表标题
        exportParams.setTitle("客户信息表");

        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, Customers.class, customersList);
        ServletOutputStream outputStream = response.getOutputStream();
        // 写出工作簿
        workbook.write(outputStream);
        workbook.close();
        outputStream.close();
    }
}




